package com.innovation.ic.im.end.base.handler.im_erp9;

import com.alibaba.fastjson.JSONObject;
import com.innovation.ic.im.end.base.model.im_erp9.UserGroupMessage;
import com.innovation.ic.im.end.base.pojo.constant.Constants;
import com.innovation.ic.im.end.base.pojo.constant.RedisStorage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.Set;

@Component
public class UserGroupMessageHandler extends ImErp9AbstractHandler {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 处理im-erp9数据库的user_group_message表的insert操作
     *
     * @param userGroupMessage
     */
    public void handleInsertUserGroupMessage(UserGroupMessage userGroupMessage) {
        logger.info("处理im-erp9数据库的user_group_message表的insert操作，向redis插入USER_GROUP_MESSAGE:开头的数据");

        // 向redis存储数据
        String key = RedisStorage.USER_GROUP_MESSAGE_PREFIX +  userGroupMessage.getUserGroupId();
        String value = JSONObject.toJSONString(userGroupMessage);
        double score = userGroupMessage.getCreateTime().getTime();
        redisManager.zAdd(key, value, score);
//        redisManager.expire(key, redisParamConfig.getTimeout());
    }

    /**
     * 处理im-erp9数据库的userGroupMessage表的update操作
     * @param userGroupMessage 更新的数据
     */
    public void handleUpdateUserGroupMessage(UserGroupMessage userGroupMessage) {
        logger.info("处理im-erp9数据库的user_group_message表的insert操作，向redis插入USER_GROUP_MESSAGE:开头的数据");

        String key = RedisStorage.USER_GROUP_MESSAGE_PREFIX + userGroupMessage.getUserGroupId();
        double score = userGroupMessage.getCreateTime().getTime();

        Set<String> stringSet = redisManager.zReverseRangeByScore(key, score, score);
        if(stringSet != null && stringSet.size() > 0){
            for(String userGroupMsg : stringSet){
                JSONObject jsonObject = JSONObject.parseObject(userGroupMsg);
                if(((Integer) jsonObject.get(Constants.ID)).intValue() == userGroupMessage.getId().intValue()){
                    // 删除redis中的值
                    redisManager.zRemove(key, userGroupMsg);
                    // 添加新的值
                    String value = JSONObject.toJSONString(userGroupMessage);
                    redisManager.zAdd(key, value, score);
                    break;
                }
            }
        }
    }
}
